import { _decorator } from 'cc'
import { DIRECTION_ENUM, ENTITY_STATE_ENUM, EVENT_ENUM } from '../Enums'
import { IEntity } from '../Levels'
import DataManager from '../Runtime/DataManager'
import EventManager from '../Runtime/EventManager'
import { EntityManager } from './EntityManager'
const { ccclass } = _decorator

@ccclass('EnemyManager')
export class EnemyManager extends EntityManager {

  async init(params: IEntity) {
    super.init(params)

    // 监听玩家出生事件
    EventManager.Instance.on(EVENT_ENUM.PLAYER_BORN, this.onChangeDirection, this)
    // 监听玩家移动结束事件,是否需要改变朝向
    EventManager.Instance.on(EVENT_ENUM.PLAYER_MOVE_END, this.onChangeDirection, this)
    // 监听被攻击事件
    EventManager.Instance.on(EVENT_ENUM.ATTACK_ENEMY, this.onDead, this)
    this.onChangeDirection(true)
  }

  onDestroy() {
    super.onDestroy()
    EventManager.Instance.off(EVENT_ENUM.PLAYER_BORN, this.onChangeDirection)
    EventManager.Instance.off(EVENT_ENUM.PLAYER_MOVE_END, this.onChangeDirection)
    EventManager.Instance.off(EVENT_ENUM.ATTACK_ENEMY, this.onDead)
  }

  // 是否改变朝向
  onChangeDirection(isInit:boolean = false) {
    if(this.state === ENTITY_STATE_ENUM.DEATH || !DataManager.Instance.player) return

    const { x: playerX, y: playerY } = DataManager.Instance.player
    /**
     * 1.以敌人为中心，画出坐标系，分为四个象限
     * 2.根据敌人和玩家的位置，判断出玩家在哪个象限
     * 3.在根据X和Y方向的差值，判断出玩家在象限中的上半部分还是下半部分
     * 4.根据以上信息，判断出敌人的朝向
     **/
    const disX = Math.abs(this.x - playerX)
    const disY = Math.abs(this.y - playerY)

    // 当玩家处于象限的中心线上时，只有初始化时才改变朝向
    if(disX === disY && !isInit) return

    if(playerX >= this.x && playerY <= this.y) {
      // 第一象限
      this.direction = disY > disX ? DIRECTION_ENUM.UP : DIRECTION_ENUM.RIGHT
    } else if(playerX <= this.x && playerY <= this.y) {
      // 第二象限
      this.direction = disY > disX ? DIRECTION_ENUM.UP : DIRECTION_ENUM.LEFT
    } else if(playerX <= this.x && playerY >= this.y) {
      // 第三象限
      this.direction = disY > disX ? DIRECTION_ENUM.DOWN : DIRECTION_ENUM.LEFT
    } else if(playerX >= this.x && playerY >= this.y) {
      // 第四象限
      this.direction = disY > disX ? DIRECTION_ENUM.DOWN : DIRECTION_ENUM.RIGHT
    }

  }



  // 死亡
  onDead(id: string) {
    console.log(`enemyID:${this.id} 状态:${this.state}`);

    if(this.state === ENTITY_STATE_ENUM.DEATH) return

    if(this.id === id) {
      this.state = ENTITY_STATE_ENUM.DEATH
    }
  }
}
